﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;

namespace RegexLib.Web.Models.Web
{
	/// <summary>
	/// 提供SEO相关功能。
	/// </summary>
	public class RxSeoUtility
	{
		public static string GetMetaKeywords()
		{
			RxSeoSettings settings = RxSeoSettings.Load();
			return settings.MetaKeywords;
		}

		public static string GetMetaDescription()
		{
			RxSeoSettings settings = RxSeoSettings.Load();
			return settings.MetaDescription;
		}
	}

	/// <summary>
	/// 来自于XML配置文件的SEO设置。配置文件位置：~/App_Data/SeoSettings.xml。
	/// </summary>
	public class RxSeoSettings
	{
		/// <summary>
		/// 获取Keywords Meta标签的内容。
		/// </summary>
		public string MetaKeywords { get; private set; }

		/// <summary>
		/// 获取Description Meta标签的内容。
		/// </summary>
		public string MetaDescription { get; private set; }

		/// <summary>
		/// 防止实例化。
		/// </summary>
		private RxSeoSettings(XmlDocument xdoc)
		{
			XmlNode keywordsNode = xdoc.SelectSingleNode("/SeoSettings/MetaKeywords");
			this.MetaKeywords = keywordsNode.InnerText.Trim();

			XmlNode descriptionNode = xdoc.SelectSingleNode("/SeoSettings/MetaDescription");
			this.MetaDescription = descriptionNode.InnerText.Trim();
		}

		/// <summary>
		/// 用于存放SEO设置的XML文件的路径。
		/// </summary>
		const string settingsPath = "~/App_Data/SeoSettings.xml";

		/// <summary>
		/// 加载SEO设置。
		/// </summary>
		/// <returns></returns>
		public static RxSeoSettings Load()
		{
			RxSeoSettings settings = RxAppDataCache.Get<RxSeoSettings>(settingsPath);

			if (settings != null)
				return settings;

			XmlDocument xdoc = new XmlDocument();
			xdoc.Load(HttpContext.Current.Server.MapPath(settingsPath));

			settings = new RxSeoSettings(xdoc);
			RxAppDataCache.Set<RxSeoSettings>(settingsPath, settings);

			return settings;
		}
	}
}
